// CSE 142, Winter 2008, Marty Stepp // // This program computes and prints prime numbers. // This is an example of a fencepost problem. public class Primes { public static void main(String[] args) { printPrimes(1); printPrimes(2); printPrimes(50); printPrimes(53); printPrimes(1000); printPrimes2(50, 100); } // Prints all prime numbers up to the given maximum. public static void printPrimes(int max) { System.out.print("["); if (max > 1) { System.out.print(2); // for each number up to max, // if that number is prime, // print that number for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { // i is prime System.out.print(", " + i); } } } System.out.println("]"); } // Prints all prime numbers between the given minimum and maximum values. public static void printPrimes2(int min, int max) { System.out.print("["); int count = 0; if (max > 1) { // for each number up to max, // if that number is prime, // print that number for (int i = min; i <= max; i++) { if (countFactors(i) == 2) { // i is prime count++; if (count > 1) { System.out.print(", "); } System.out.print(i); } } } System.out.println("]"); } // Returns the number of factors of the given integer. // Assumes that a non-negative number is passed. // (This code comes from a previous lecture.) public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { // i is a factor of the number count++; } } return count; } }